package com.zsc.newbuds.config;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.io.StringWriter;

/**序列化转json
 * @author D
 */
@Configuration
public class JacksonAllConfig {


    public String serialize(Object object){
        String json = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            StringWriter stringWriter = new StringWriter();
            JsonGenerator jsonGenerator = new JsonFactory().createJsonGenerator(stringWriter);
            objectMapper.writeValue(jsonGenerator, object);
            jsonGenerator.close();
            json = stringWriter.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }

    public Object deserialize(String json){
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(json, Object.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
